<template>
  <div>
    <AxiomToolbar>
      <AxiomGroup justify="space-between" align="center" class="w-100">
        <AxiomTitle title="知识库管理" />
        <AxiomButton icon="plus" type="primary" @click="handleOpenCreateDialog">新建知识库</AxiomButton>
      </AxiomGroup>
    </AxiomToolbar>

    <AxiomSection>
      <KnowledgeBaseList
        ref="knowledgeBaseListRef"
        @edit-knowledge-base="handleOpenEditDialog"
      />
    </AxiomSection>

    <!-- 新建/编辑知识库弹窗 -->
    <AxiomDialog
      v-model="formDialogVisible"
      :title="isEditMode ? '编辑知识库' : '新建知识库'"
      @confirm="handleConfirm"
      @open="fetchEmbeddingProfiles"
    >
      <AxiomForm v-if="formDialogVisible" ref="formRef" :model="form" label-width="120px">
        <AxiomFormItem label="显示名称" prop="name" :rules="{ required: true, message: '请输入显示名称' }">
          <AxiomInput v-model="form.name" />
        </AxiomFormItem>
        <AxiomFormItem label="描述" prop="description">
          <AxiomInput v-model="form.description" type="textarea" />
        </AxiomFormItem>
        <AxiomFormItem label="模型组" prop="embedding_profile_group_id" :rules="{ required: true, message: '请选择模型组' }">
            <AxiomSelect
                v-model="form.embedding_profile_group_id"
                placeholder="选择用于文档处理和向量化的模型组"
                :options="groupOptions"
                :loading="embeddingProfilesLoading"
                :disabled="isEditMode"
                block
                style="width: 60%;"
            />
        </AxiomFormItem>
        <AxiomFormItem label="索引模型" prop="indexing_embedding_profile" :rules="{ required: true, message: '请选择索引模型' }">
            <AxiomSelect
                v-model="form.indexing_embedding_profile"
                placeholder="选择用于文档处理和向量化的模型"
                :options="indexingProfileOptions"
                :loading="embeddingProfilesLoading"
                :disabled="isEditMode"
                block
                style="width: 60%;"
            />
        </AxiomFormItem>
        <AxiomFormItem label="查询模型" prop="query_embedding_profile" :rules="{ required: true, message: '请选择查询模型' }">
            <AxiomSelect
                v-model="form.query_embedding_profile"
                placeholder="选择用于理解用户问题的模型"
                :options="queryProfileOptions"
                :loading="embeddingProfilesLoading"
                :disabled="isEditMode"
                block
                style="width: 60%;"
            />
        </AxiomFormItem>
      </AxiomForm>
    </AxiomDialog>
  </div>
</template>

<script setup>
import { ref, inject, computed, watch } from 'vue';
import {
  AxiomToolbar,
  AxiomGroup,
  AxiomButton,
  AxiomTitle,
  AxiomSection,
  AxiomDialog,
  AxiomForm,
  AxiomFormItem,
  AxiomInput,
  AxiomSelect,
} from 'axiom-view';
import { knowledgeBaseApi } from '@/api/knowledge/knowledgeBase.js';
import KnowledgeBaseList from './components/KnowledgeBaseList.vue';

const { notification } = inject('axiom-utils');

const knowledgeBaseListRef = ref(null);

const isEditMode = ref(false);
const formDialogVisible = ref(false);
const formRef = ref(null);
const form = ref({
  id: null,
  name: '',
  description: '',
  embedding_profile_group_id: null,
  indexing_embedding_profile: null,
  query_embedding_profile: null,
});

const embeddingProfilesLoading = ref(false);
const embeddingProfileGroups = ref([]);
const selectedGroupId = computed(() => form.value.embedding_profile_group_id);

const groupOptions = computed(() => {
    return embeddingProfileGroups.value.map(group => ({
        label: group.group_display_name,
        value: group.group_id,
    }));
});

const indexingProfileOptions = computed(() => {
    if (!selectedGroupId.value) return [];
    const group = embeddingProfileGroups.value.find(g => g.group_id === selectedGroupId.value);
    return group ? group.indexing_models.map(p => ({ label: p.display_text, value: p.profile_name })) : [];
});

const queryProfileOptions = computed(() => {
    if (!selectedGroupId.value) return [];
    const group = embeddingProfileGroups.value.find(g => g.group_id === selectedGroupId.value);
    return group ? group.querying_models.map(p => ({ label: p.display_text, value: p.profile_name })) : [];
});

watch(selectedGroupId, (newVal, oldVal) => {
    if (newVal !== oldVal) {
        form.value.indexing_embedding_profile = null;
        form.value.query_embedding_profile = null;
    }
});

function handleOpenCreateDialog() {
  isEditMode.value = false;
  form.value = {
    id: null,
    name: '',
    description: '',
    embedding_profile_group_id: null,
    indexing_embedding_profile: null,
    query_embedding_profile: null,
  };
  formDialogVisible.value = true;
}

function handleOpenEditDialog(knowledgeBase) {
    isEditMode.value = true;
    form.value = { 
        id: knowledgeBase.id, 
        name: knowledgeBase.name, 
        description: knowledgeBase.description,
        embedding_profile_group_id: knowledgeBase.embedding_profile_group_id,
        indexing_embedding_profile: knowledgeBase.indexing_embedding_profile,
        query_embedding_profile: knowledgeBase.query_embedding_profile,
    };
    formDialogVisible.value = true;
}

async function fetchEmbeddingProfiles() {
    if (embeddingProfileGroups.value.length > 0) return;
    
    embeddingProfilesLoading.value = true;
    try {
        const res = await knowledgeBaseApi.getEmbeddingProfileGroups();
        embeddingProfileGroups.value = res.data || [];
    } catch (error) {
        console.error(error);
        notification.error({ title: '错误', message: '加载 Embedding 模型配置失败' });
    } finally {
        embeddingProfilesLoading.value = false;
    }
}

async function handleConfirm() {
  const isValid = await formRef.value.validate();
  if (!isValid) return;

  try {
    const payload = {
        name: form.value.name,
        description: form.value.description,
    };

    if (isEditMode.value) {
        payload.embedding_profile_group_id = form.value.embedding_profile_group_id;
        payload.indexing_embedding_profile = form.value.indexing_embedding_profile;
        payload.query_embedding_profile = form.value.query_embedding_profile;
        
        await knowledgeBaseApi.update(form.value.id, payload);
        notification.success({ title: '成功', message: '知识库更新成功' });
    } else {
        payload.embedding_profile_group_id = form.value.embedding_profile_group_id;
        payload.indexing_embedding_profile = form.value.indexing_embedding_profile;
        payload.query_embedding_profile = form.value.query_embedding_profile;

        await knowledgeBaseApi.create(payload);
        notification.success({ title: '成功', message: '知识库创建成功' });
    }
    formDialogVisible.value = false;
    if (knowledgeBaseListRef.value) {
       knowledgeBaseListRef.value.fetchKnowledgeBases();
    }
  } catch (error) {
    console.error(error);
  }
}
</script> 